local ESCHSTAT=require'zdc.typetsk'.ESCHSTAT
local cornutil=require'zdc.cornutil'
module(..., package.seeall)

local function init_sch(t,ts,args)
	local corn=cornutil.new(args.schedule)
	local param=args.ts_start
	if param then
		t.ts_start= param
	end
	param=args.ts_end
	if param then
		t.ts_end=param
	end
	param=args.schedule
	if param then
		t.schedule=param
	end
	param=args.taction
	if param then
		t.taction=param
	end
	param=args.targs
	if param then
		t.targs=param
	end
	t.stat=ESCHSTAT.queue
	t.stat_ts=ts
	t.ts_next=corn:getTimeAfter(ts) or 0
	t:__set_ik(ts)
end
local function get_schdef(n)
	return {
		ts_create=n.ts_create;
		schedule=n.schedule;
		ts_next=n.ts_next;
		ts_last=n.ts_last;
		noskip=n.noskip;
		taction=n.taction;
		targs=n.targs;
		stat=n.stat;
		stat_ts=n.stat_ts;
	}
end

function AddSchedule(user,dal,n,act,args)
	local ts=os.time()
	local oid=args.id
	local child =n:__add_child(oid)
	child.ts_create = ts
	init_sch(child,ts,args)
	n:__save_ta()
	dal:CommitTA()
	return oid
end

function CalcSchedule(user,dal,n,act,args)
	local cn,lst=dal:GetChildNodesEx(n.__id)--,'EQ(stat,1)')
	local rt={}
	local ts=args.ts or os.date()
	for i,k in ipairs(lst) do
		local v=cn[k]
		if v.stat==ESCHSTAT.queue then
			table.insert(rt,{tskid=v.__id,taskdef=get_schdef(v)})
		end
	end
	return rt
end

--------------- schedule action -------------
function AddResult(user,dal,n,act,args)
	local ts=args.ts
	local oid=tostring(ts)
	local child=n/oid
	if child then return oid end
	local child =assert(n:__add_child(oid))
	assert(child('_init', ts,args))
	if ts >= n.ts_last then
		n.ts_last=ts
	end
	if ts >= n.ts_next then
		local corn=cornutil.new(n.schedule)
		local nowts=n.noskip and n.ts_next or os.time()
		n.ts_next=corn:getTimeAfter(nowts) or 0
	end
	n:__save_ta()
	dal:CommitTA()
	return oid
end

function SetSchStat(user,dal,n,act,args)
	if args.stat then
		n.stat=args.stat
		n.stat_ts=os.date()
		if ESCHSTAT.queue~=n.stat then
			n.ts_next=0
		end
		n:__save_ta()
		dal:CommitTA()
	end
	return true
end

